package com.zx.mobile.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.zx.map.dao.model.StoreInfo;
import com.zx.map.service.BaseAcctInfoService;
import com.zx.map.service.EncashLogService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.OrdLogService;
import com.zx.map.service.RiskControlService;
import com.zx.map.service.StoreInfoService;
import com.zx.map.service.domain.OrdLogDomain;
import com.zx.map.service.model.BaseAcctInfoModel;
import com.zx.map.service.model.EncashLogModel;
import com.zx.map.service.model.EncashResponse;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.OrdLogModel;
import com.zx.map.service.model.RiskControlModel;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.SUConstants;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.SessionHelper;
import com.zx.mobile.domain.EncashApplyDomain;
import com.zx.mobile.domain.EncashQueryDomain;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.mobile.domain.SendVerifyCodeRequest;
import com.zx.mobile.domain.SendVerifyCodeResponse;
import com.zx.mobile.service.proxy.EncashCommonProxy;
import com.zx.mobile.service.proxy.EncashQueryProxy;
import com.zx.mobile.service.proxy.MessageSendProxy;
import com.zx.mobile.service.proxy.OrderQueryProxy;
import com.zx.mobile.utils.WebUtils;
import com.zx.platform.utils.MD5Util;
import com.zx.platform.utils.PmpUtils;
import com.zx.scp.service.model.MessageResponse;
import com.zx.scp.utils.PropertyUtil;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-7-5 Time: 下午8:09 To
 * change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/mobile/index")
public class MobileIndexController {
    /**
     * log
     */
    private static Logger log = Logger.getLogger(MobileIndexController.class);
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private OrdLogService ordLogService;
    @Autowired
    private BaseAcctInfoService baseAcctInfoService;
    @Autowired
    private EncashLogService encashLogService;
    @Autowired
    private RiskControlService riskControlService;

    @Autowired
    private StoreInfoService storeInfoService;
    /**
     * 我的钱包
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/mywallet")
    public String mywallet(Model model, HttpServletRequest request) {
        try {
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            BaseAcctInfoModel temp = baseAcctInfoService.getModelByKey(user
                    .getMerchantInfoDetailModel().getMerchantId());
            model.addAttribute("model", temp);
            return "/jsp/mobile/mywallet";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 门店收款
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/shopIncome")
    public String shopIncome(Model model, HttpServletRequest request) {
        return "/jsp/mobile/shopIncome/shopIncome";
    }

    /**
     * 验证码发送接口
     *
     * @param sendVerifyCodeRequest
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/getPwdVerifyCode")
    @ResponseBody
    public SendVerifyCodeResponse sendVerifyCode(
            SendVerifyCodeRequest sendVerifyCodeRequest, Model model,
            HttpServletRequest request) {
        SendVerifyCodeResponse sendVerifyCodeResponse = new SendVerifyCodeResponse();
        log.info("调用参数:"
                + ToStringBuilder.reflectionToString(sendVerifyCodeRequest));
        try {
            MerchantInfoModel temp = merchantInfoService
                    .getMerchantInfoModelBySysAccount(sendVerifyCodeRequest
                            .getTelephone());
            if (null != temp) {
                if (StringUtils
                        .isNotBlank(sendVerifyCodeRequest.getTelephone())) {
                    // 传递订单号及订单金额
                    MessageResponse response = MessageSendProxy
                            .getMessageResponse(
                                    MobileCommonHelper.MESSAGETYPE_FORGETPWD,
                                    sendVerifyCodeRequest.getTelephone());
                    if (null != response
                            && "0000".equals(response.getReturnCode())) {
                        // 2、验证用户名及密码
                        sendVerifyCodeResponse.setReturnCode("0000");
                        sendVerifyCodeResponse.setReturnMsg("验证码发送成功");
                    } else {
                        // 2、验证用户名及密码
                        sendVerifyCodeResponse.setReturnCode("9999");
                        sendVerifyCodeResponse.setReturnMsg(response
                                .getErrMsg());
                    }
                } else {
                    sendVerifyCodeResponse.setReturnCode("0002");
                    sendVerifyCodeResponse.setReturnMsg("手机号为空");
                }
            } else {
                sendVerifyCodeResponse.setReturnCode("9999");
                sendVerifyCodeResponse.setReturnMsg("输入错误");
            }
        } catch (Exception e) {
            log.error("系统内部异常", e);
            sendVerifyCodeResponse.setReturnCode("9999");
            sendVerifyCodeResponse.setReturnMsg("系统内部异常");
        }
        return sendVerifyCodeResponse;
    }

    /**
     * 刷卡收款
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/cardincome")
    public String cardincome(Model model, HttpServletRequest request) {
        try {
            return "/jsp/mobile/cardincome";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 刷卡收款处理
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/cardincomedeal")
    public String cardincomedeal(String incomeAmt, Model model,
                                 HttpServletRequest request) {
        try {
            model.addAttribute("incomeAmt", incomeAmt);
            return "/jsp/mobile/cardincomeresult";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 首页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model, HttpServletRequest request) {
        return "/jsp/mobile/main";
    }

    /**
     * 手机端查询 作为商户查询自己 交易查询
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/orderquery")
    public String orderquery(OrdLogDomain ordQueryDomain, Model model, HttpServletRequest request) {
        try {
            log.debug("查询收款交易：" + ToStringBuilder.reflectionToString(ordQueryDomain));
            // 设置查询商户id 查询交易数据list
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            ordQueryDomain=OrderQueryProxy.transformQueryDomain(user,ordQueryDomain);
            ordQueryDomain.setTransStatus("s");

            List<OrdLogModel> ordList = ordLogService.getListByOrdLogDomain(null,ordQueryDomain);
            // 统计汇总交易数据
            Map<String, Object> map = OrderQueryProxy.transformOrdList(ordList);
            model.addAttribute("ordQueryDomain", ordQueryDomain);
            model.addAttribute("list", map.get("list"));
            model.addAttribute("totalAmt", map.get("totalAmt"));
            return "/jsp/mobile/orderdetail";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "交易查询出错了");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 取现查询
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/encashquery")
    public String encashquery(EncashQueryDomain encashQueryDomain, Model model,
                              HttpServletRequest request) {
        try {
            log.debug("查询取现交易："
                    + ToStringBuilder.reflectionToString(encashQueryDomain));
            // 设置查询商户id 查询交易数据list
            MobileUserDomain user = WebUtils.queryCurrentLoginInfo(request);
            encashQueryDomain = EncashQueryProxy.transformQueryDomain(user,
                    encashQueryDomain);
            List<EncashLogModel> encashLogModels = encashLogService
                    .getListByDomain(encashQueryDomain);
            // 统计汇总交易数据
            Map<String, Object> map = EncashQueryProxy
                    .transformOrdList(encashLogModels);
            model.addAttribute("encashQueryDomain", encashQueryDomain);
            model.addAttribute("list", map.get("list"));
            model.addAttribute("totalAmt", map.get("totalAmt"));
            return "/jsp/mobile/encashdetail";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "交易查询出错了");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 余额取现
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/enchash")
    public String enchash(Model model, HttpServletRequest request) {
        try {
            MobileUserDomain user = WebUtils.queryCurrentLoginInfo(request);
            //获取最新数据
            MerchantInfoModel currentModel = merchantInfoService.getModelByKey(user.getMerchantInfoDetailModel().getMerchantId());
            //交易密码不为空的情况下  允许用户进行设置密码
            //若交易密码为空 需要用户先设置密码
            if (StringUtils.isNotBlank(currentModel.getTradePassword())) {
                if (MobileCommonHelper.APPUSERSTATUS_NORMARL.equals(currentModel.getStatus())) {
                    BaseAcctInfoModel temp = baseAcctInfoService.getModelByKey(user
                            .getMerchantInfoDetailModel().getMerchantId());
                    //获取T0取现状态
                    String t0RunStatus = PropertyUtil.getValue("t0RunStatus");
                    model.addAttribute("t0RunStatus", t0RunStatus);
                    model.addAttribute("model", temp);
                    return "/jsp/mobile/enchash";
                } else {
                    model.addAttribute("userStatus", currentModel.getStatus());
                    return "/jsp/mobile/userbindcardnotice";
                }
            } else {
                model.addAttribute("operatorType", MobileCommonHelper.URLRETURN_ENCHASH);//设置交易密码 回退到修改交易密码
                return "/jsp/mobile/pwd/setpaypwd";
            }
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 余额取现结果页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/enchashresult")
    public String enchashresult(EncashApplyDomain encashApplyDomain,
                                Model model, HttpServletRequest request) {
        try {
            log.debug("取现交易："
                    + ToStringBuilder.reflectionToString(encashApplyDomain));
            // 验证交易密码是否正确
            MobileUserDomain user = WebUtils.queryCurrentLoginInfo(request);
            //事中风控 对交易金额进行限制
            String riskTransCode = "0".equals(encashApplyDomain.getEncashType()) ? SUConstants.TRANSTYPE_T0ENCASH : SUConstants.TRANSTYPE_T1ENCASH;
            RiskControlModel riskControlModel = riskControlService.bussinessAmtRiskControl(riskTransCode, encashApplyDomain.getEncashAmt(), user.getMerchantInfoDetailModel());
            if (MobileCommonHelper.RISKPASSCODE.equals(riskControlModel.getRiskCode())) {//如果风控通过交易限额
                RiskControlModel timeLimitRisk = riskControlService.bussinessTimeRiskControl(riskTransCode, encashApplyDomain.getEncashAmt(), user.getMerchantInfoDetailModel());
                if (MobileCommonHelper.RISKPASSCODE.equals(timeLimitRisk.getRiskCode())) {//如果风控通过交易限次
                    String tradePwd = PmpUtils.encoderByMD5(MD5Util
                            .getMD5Str(encashApplyDomain.getTradePwd()));
                    //获取最新数据
                    MerchantInfoModel currentModel = merchantInfoService.getModelByKey(user.getMerchantInfoDetailModel().getMerchantId());
                    if (!tradePwd.equals(currentModel.getTradePassword())) {
                        model.addAttribute("errorMsg", "交易密码错误");
                        return "/jsp/mobile/error";
                    } else {
                        // 取现 记录操作流水
                        EncashLogModel param = EncashCommonProxy.transformEncachLog(
                                user, encashApplyDomain);
                        EncashResponse encashResponse = new EncashResponse();
                        // T+0取现 结算
                        if (MobileCommonHelper.ENCASHTYPE_T0.equals(encashApplyDomain
                                .getEncashType())) {
                            encashResponse = encashLogService.dealEncashLogT0(param, user
                                    .getMerchantInfoDetailModel()
                                    .getSettleCardInfoModel());
                        } else if (MobileCommonHelper.ENCASHTYPE_T1.equals(encashApplyDomain
                                .getEncashType())) {
                            encashResponse = encashLogService.dealEncashLogT1(param, user
                                    .getMerchantInfoDetailModel()
                                    .getSettleCardInfoModel());
                        }
                        if ("0000".equals(encashResponse.getReturnCode())) {

                            model.addAttribute("model", encashApplyDomain);
                            return "/jsp/mobile/enchashsuccess";
                        } else {
                            model.addAttribute("errorMsg", encashResponse.getErrMsg());
                            return "/jsp/mobile/error";
                        }
                    }
                } else {
                    model.addAttribute("errorMsg", timeLimitRisk.getRiskMsg());
                    log.error("未通过系统风控" + timeLimitRisk.getRiskMsg());
                    return "/jsp/mobile/error";
                }
            } else {
                model.addAttribute("errorMsg", riskControlModel.getRiskMsg());
                log.error("未通过系统风控" + riskControlModel.getRiskMsg());
                return "/jsp/mobile/error";
            }
        } catch (Exception e) {
            model.addAttribute("errorMsg", e.getMessage());
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }


    /**
     * 结算卡页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/settlecard")
    public String settlecard(Model model, HttpServletRequest request) {
        try {
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            String merchantId = user.getMerchantInfoDetailModel()
                    .getMerchantId();
            user = MobileControlHelper.reloadSessionInfoByMerchantId(merchantInfoService, merchantId, user.getKeepKey(), request);
            String userStatus = user.getMerchantInfoDetailModel().getStatus();
            if (MobileCommonHelper.APPUSERSTATUS_NORMARL.equals(userStatus)) {
                return "/jsp/mobile/settlecard";
            } else {
                model.addAttribute("userStatus", userStatus);
                return "/jsp/mobile/userbindcardnotice";
            }
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 实名认证页面
     *
     * @param model
     * @param request
     * @return
     */
//    @RequestMapping("/auth")
//    public String auth(Model model, HttpServletRequest request) {
//        try {
//            MobileUserDomain user = (MobileUserDomain) request.getSession()
//                    .getAttribute(SessionHelper.MOBILEUSER);
//            String merchantId = user.getMerchantInfoDetailModel()
//                    .getMerchantId();
//            user = MobileControlHelper.reloadSessionInfoByMerchantId(merchantInfoService, merchantId, user.getKeepKey(), request);
//            String userStatus = user.getMerchantInfoDetailModel().getStatus();
//            if (MobileCommonHelper.APPUSERSTATUS_NORMARL.equals(userStatus)) {
//                return "/jsp/mobile/auth";
//            } else {
//                model.addAttribute("userStatus", userStatus);
//                return "/jsp/mobile/userbindcardnotice";
//            }
//        } catch (Exception e) {
//            model.addAttribute("errorMsg", "系统异常");
//            log.error("系统异常", e);
//            return "/jsp/mobile/error";
//        }
//    }
    @RequestMapping("/auth")
    @ResponseBody
    public Map auth(HttpServletRequest request) {
    	try {
    		  Map<String, String> result = new HashMap<>();
	          MobileUserDomain user = (MobileUserDomain) request.getSession().getAttribute(SessionHelper.MOBILEUSER);
	          String merchantId = user.getMerchantInfoDetailModel().getMerchantId();
	          user = MobileControlHelper.reloadSessionInfoByMerchantId(merchantInfoService, merchantId, user.getKeepKey(), request);
	          String userStatus = user.getMerchantInfoDetailModel().getStatus();
	          if (MobileCommonHelper.APPUSERSTATUS_NORMARL.equals(userStatus)) {
	        	  StoreInfo storeInfo = storeInfoService.find(merchantId);
	        	  
	        	  result.put("userStatus", userStatus);
	        	  result.put("businessLicenseImg", storeInfo.getBusinessLicenseImg());
	        	  result.put("holdLicenseImg", storeInfo.getHoldLicenseImg());
	        	  result.put("storeInImg", storeInfo.getStoreInImg());
	        	  result.put("storeOutImg", storeInfo.getStoreOutImg());
	        	  result.put("idPositiveImg", storeInfo.getIdPositiveImg());
	        	  result.put("idNegativeImg", storeInfo.getIdNegativeImg());
	        	  
	          }
	          result.put("userStatus", userStatus);
          return CommonResponseUtils.successResponse(result);
    	}catch(Throwable e) {
    		e.printStackTrace();
    		return CommonResponseUtils.failureResponse(e.getMessage());
    	}
    }

    /**
     * 关于我们页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/about")
    public String about(Model model, HttpServletRequest request) {
        return "/jsp/mobile/about";
    }

    /**
     * 查询特定订单状态
     *
     * @return
     */
    @RequestMapping("/queryOrderStatus")
    @ResponseBody
    public Map<String, String> queryOrderStatus(String orderId,
                                                HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            OrdLogModel ordLogModel = ordLogService.getModelByKey(orderId);
            if (null != ordLogModel
                    && ("S".equals(ordLogModel.getTransStatus()) || "F"
                    .equals(ordLogModel.getTransStatus()))) {
                map.put("transStatus", ordLogModel.getTransStatus());// 成功或失败终态
            } else {
                map.put("transStatus", "N");// 初始状态
            }
            request.getSession().setAttribute("ordLogModel", ordLogModel);
        } catch (Exception e) {
            map.put("transStatus", "N");// 初始状态
            log.error("查询未处理订单失败" + e.getMessage(), e);
        }
        return map;
    }

    /**
     * 获取阿里云oss token
     *
     * @return
     */
    @RequestMapping("/sts")
    @ResponseBody
    public Map sts( HttpServletRequest request) {
    	try {
    		return CommonResponseUtils.successResponse(getsts());
		} catch (Throwable e) {
			e.printStackTrace();
			return CommonResponseUtils.failureResponse(e.getMessage());
		}

	
    }

    
	// 目前只有"cn-hangzhou"这个region可用, 不要使用填写其他region的值
	  public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
	  // 当前 STS API 版本
	  public static final String STS_API_VERSION = "2015-04-01";
	  static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,
	                                       String roleArn, String roleSessionName, String policy,
	                                       ProtocolType protocolType) throws ClientException {
	    try {
	      // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
	      IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
	      DefaultAcsClient client = new DefaultAcsClient(profile);
	      // 创建一个 AssumeRoleRequest 并设置请求参数
	      final AssumeRoleRequest request = new AssumeRoleRequest();
	      request.setVersion(STS_API_VERSION);
	      request.setMethod(MethodType.POST);
	      request.setProtocol(protocolType);
	      request.setRoleArn(roleArn);
	      request.setRoleSessionName(roleSessionName);
	      request.setPolicy(policy);
	      // 发起请求，并得到response
	      final AssumeRoleResponse response = client.getAcsResponse(request);
	      return response;
	    } catch (ClientException e) {
	      throw e;
	    }
	  }
	  public static AssumeRoleResponse getsts() {
	    // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
	    // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
	    // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
	    String accessKeyId = "LTAItdazdMHIUnaF";
	    String accessKeySecret = "4lnve3QuXDPCDbfb3lWGtvFGLiOyoY";
	    // AssumeRole API 请求参数: RoleArn, RoleSessionName, Policy, and DurationSeconds
	    // RoleArn 需要在 RAM 控制台上获取
	    String roleArn = "acs:ram::1648505125087678:role/aliyunosstokengeneratorrole";
	    // RoleSessionName 是临时Token的会话名称，自己指定用于标识你的用户，主要用于审计，或者用于区分Token颁发给谁
	    // 但是注意RoleSessionName的长度和规则，不要有空格，只能有'-' '_' 字母和数字等字符
	    // 具体规则请参考API文档中的格式要求
	    String roleSessionName = "alice-001";
	    // 如何定制你的policy?
	    String policy = "{\n" +
	            "    \"Version\": \"1\", \n" +
	            "    \"Statement\": [\n" +
	            "        {\n" +
	            "            \"Action\": [\n" +
	            "                \"oss:*\" \n" +
	           
	            "            ], \n" +
	            "            \"Resource\": [\n" +
	            "                \"acs:oss:*:*:*\"\n" +
	            "            ], \n" +
	            "            \"Effect\": \"Allow\"\n" +
	            "        }\n" +
	            "    ]\n" +
	            "}";
	    // 此处必须为 HTTPS
	    ProtocolType protocolType = ProtocolType.HTTPS;
	    try {
	      final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
	              roleArn, roleSessionName, policy, protocolType);
	      return response;
	    } catch (ClientException e) {
	    }
	    return null;
	  }
	  
	
}
